import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveAction;

@AllArgsConstructor
public abstract class ChainTask extends RecursiveAction {
    @Getter
    private int taskNumber;

    protected abstract void doAction(int firstNumber, int lastNumber) throws InterruptedException;

    protected abstract ForkJoinTask<Void> forkTask();

    protected void nextChain() {
    }

    @Override
    protected void compute() {
        if (taskNumber > Loader.getNumberOfThreads()) {
            nextChain();
            return;
        }

        ForkJoinTask<Void> child = forkTask();

        int numbersPerTask = (int) Math.ceil(999.0 / Loader.getNumberOfThreads());
        int firstNumber = (taskNumber - 1) * numbersPerTask + 1;
        int lastNumber = Math.min(999, taskNumber * numbersPerTask);

        try {
            doAction(firstNumber, lastNumber);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        child.join();
    }
}
